<template>
  <el-dialog
    class="preview-file-wrap"
    width="700px"
    :title="title"
    top="5vh"
    :visible.sync="dialogVisible"
    :close-on-click-modal="false"
  >
    
    <video
      v-if="dialogVisible && type==='video'"
      class="video"
      autoplay
      :src="url"
      controls="controls"
    >您的浏览器不支持视频video标签。</video>
    <audio v-if="dialogVisible && type==='audio'" :src="url" controls="controls">您的浏览器不支持音频audio标签。</audio>

    <el-row class="audio" v-if="type==='amr'">
      <el-col :span="2">
        <i class="el-icon-video-play audioBtn" @click="playUrl" v-show="isPlay"></i>
        <i class="el-icon-video-pause audioBtn" @click="playUrl" v-show="!isPlay"></i>
      </el-col>
      <el-col :span="22">
        <el-slider class="progress" v-model="currentTime" :max="amrTime"></el-slider>
      </el-col>
    </el-row>

    <template v-if="type==='img'">
      <!--轮播-->
        <el-carousel ref="carouselImg" :initial-index="index" :height="height" :autoplay="false" trigger="click" @change="change">
          <el-carousel-item v-for="item in urls" :key="item">
            <img ref="contentImg" :src="item" class="avatar">
          </el-carousel-item>
        </el-carousel>
    </template>
  </el-dialog>
</template>

<script>
const BenzAMRRecorder = require("benz-amr-recorder");

export default {
  name: "index",
  props: {
    url: {
      type: [String, Array],
      default: "https://www.w3school.com.cn/i/movie.ogg"
    },
    index:{
      type:Number,//当url为数组的时候当前选中的下标
      default:0
    },
    type: {
      type: String,
      default: "video" // ['audio', 'video', 'img', 'file', 'amr'] // amr 是amr格式音频播放的方式
    }
  },
  data() {
    return {
      dialogVisible: false,
      amrTime: 0, // 录音的总时长
      currentTime: 0, // 播放的当前时长
      isPlay: true, // 是否播放,
      arm: null,
      getCurrentTime: null, // 获取当前时长的定时器,
      heights:[],//当前选中图片的高度
      height:"500px"
    };
  },
  computed: {
    title() {
      return this.type === "audio" || this.type === "amr"
        ? "录音播放"
        : "预览查看";
    },
    urls(){
      return Array.isArray(this.url)?this.url:[this.url];
    }
  },
  watch: {
    dialogVisible(v) {
      if (v && this.type === "amr") {
        this.amr = new BenzAMRRecorder();
        // 初始化
        this.amr.initWithUrl(this.url).then(() => {
          this.playUrl();
          this.amrTime = this.amr.getDuration(); // 音频总时长
        });
      }
      //图片高度初始化
      if(v&& this.type === "img"){
        this.jisuanHeight();
      }
    },
    isPlay(v) {
      if (!v) {
        this.getCurrentTime = setInterval(() => {
          this.currentTime = this.amr.getCurrentPosition();
        }, 600);
      } else {
        clearInterval(this.getCurrentTime);
      }
      this.amr.onEnded(() => {
        this.isPlay = true;
        this.currentTime = 0;
      });
    }
  },
  methods: {
    show() {
      this.$nextTick(() => {
        if (this.type === "file") {
          this.$confirm("该文件不支持预览,是否下载该文件", "提示", {
            confirmButtonText: "下载",
            showCancelButton: false,
            closeOnClickModal: false,
            type: "warning"
          }).then(async () => {
            const url = location.origin + this.url;
            window.open(url);
          });
          return;
        }
        /* if (!this.valid()) {
          this.$message.error('文件格式不支持')
          return
        }*/
        this.dialogVisible = true;
      });
    },
    valid() {
      const m = this.url.match(/\.(\w+)(#|\?|$)/);
      const fileType = ((m && m[1]) || "").toString().toLowerCase();
      const allowHook = {
        video: ["mp4", "ogv", "ogg", "webm"],
        audio: ["wav", "mp3", "ogg", "acc", "webm"],
        img: ["jpg", "jpeg", "png", "gif"],
        amr: ["amr"] // amr文件特殊处理
      };
      return (allowHook[this.type] || []).includes(fileType);
    },
    // 播放amr格式文件
    playUrl() {
      this.isPlay = !this.isPlay;
      this.amr.playOrPauseOrResume();
    },
    async jisuanHeight(){
      let urls = Array.isArray(this.url)?this.url:[this.url];
      for (const url of urls) {
       let img = await loadImg(url);//因为当前加载完成  所以下面可以获取图片的高度了
      }
      this.heights = this.$refs.contentImg.map(m=>(m.height<=200?200:m.height)+"px");
      this.change(this.index);
    },
    change(newIndex,oldIndex){
      this.height = this.heights[newIndex];
      this.$refs.carouselImg.setActiveItem(newIndex);
    }
  }
};

function loadImg(src) {
  return new Promise((reslove, reject) => {
    let img = new Image();
    img.onload = function() {
      reslove(img)
    }
    img.onerror = function() {
      console.error("图片" + src + "加载失败");
      reslove(img)
    }
    img.src = src;
  });
}

</script>

<style scoped lang="scss">
audio,
video,
img {
  width: 100%;
}
video {
  height: 500px;
}
</style>
<style lang="scss">
.preview-file-wrap {
  .audio {
    width: 100%;
    height: 50px;
    background-color: #ccc;
    padding: 0 8px;
    .el-col {
      height: 100%;
    }
    .audioBtn {
      font-size: 32px;
      margin-top: 12px;
      margin-left: 5px;
      cursor: pointer;
    }
    .progress {
      margin-top: 10px;
    }
  }
}
</style>

<style scoped>
</style>